
package com.ifcar.app.activity;

import java.lang.ref.WeakReference;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.ShowBigView;
import com.ifcar.app.view.ShowBigView.onClickCallBack;
import com.ifcar.app.activity.R;

public class ShowBigPic extends BaseActivity {

    private String imgSrcString = "";
    private String imgOrgString = "";
    private String altString = "";
    private String downloadimgSrcString = "";
    private Bitmap imgBm = null;

    private ShowBigView bigpicImg;
    private TextView bigpicDesc;
    private ImageButton showpicButton;
    private ImageButton downloadButton;
    private LinearLayout loadingLayout;
    private FrameLayout bigpicLinearLayout;

    private Animation slideTopIn;
    private Animation slideTopOut;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.showbigpic);
        findViewsById();
        setListeners();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setTextViewColor(this, R.id.bigpic_desc,
                R.color.bigimg_text_desc_color);

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            downloadimgSrcString = bundle
                    .getString(GetColumnsInfo.DOWNLOAD_IMGSRC_TAG);
            imgSrcString = downloadimgSrcString.replace("_small", "");

            imgOrgString = bundle.getString(GetColumnsInfo.ORG_IMAGE_TAG);
            altString = bundle.getString(GetColumnsInfo.ALT_TAG);
            try {
                altString = Tools.htmlDecoder(altString);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (imgSrcString != null && !imgSrcString.equals("")) {
            showLoadingLayout();
            if (PicUtil.isLocalPicExit(PicUtil.phototempDir, imgSrcString
                    .substring(imgSrcString.lastIndexOf("/") + 1,
                            imgSrcString.length()))) {
                hideLoadingLayout();

                WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(
                        PicUtil.readLocalJPEGFile(PicUtil.phototempDir,
                                imgSrcString.substring(
                                        imgSrcString.lastIndexOf("/") + 1,
                                        imgSrcString.length())));
                imgBm = bitmapReference.get();

                if (null == imgBm) {
                    getNetworkImage();
                } else {
                    bigpicImg.setImageBitmap(imgBm);

                    bigpicImg.setAnimation(slideTopIn);

                    if (altString != null && !altString.equals("")) {
                        bigpicDesc.setVisibility(View.VISIBLE);
                        String t = altString;
                        if (1 == screentype)
                            t = t.length() > 22 ? t.substring(0, 20) + ".." : t;
                        bigpicDesc.setText(t);

                    } else {

                    }
                    bigpicLinearLayout.setVisibility(View.VISIBLE);
                }
            } else {

                getNetworkImage();

            }

        }

       
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (bigpicImg != null) {
            bigpicImg.setScale(getWindow().getWindowManager().getDefaultDisplay()
                    .getWidth(), getWindow().getWindowManager().getDefaultDisplay()
                    .getHeight());
            
            if (imgBm != null)
                bigpicImg.setImageBitmap(imgBm);
//            else
//                bigpicImg.setImageBitmap();

            bigpicImg.requestLayout();
        }

    }

    private void getNetworkImage() {
        // TODO Auto-generated method stub
        if (Tools.CheckNetwork(ShowBigPic.this)) {
            new Thread() {
                public void run() {
                    if (!Tools.CheckNetwork(ShowBigPic.this)) {
                        imgBm = null;
                    } else {
                        imgBm = PicUtil.getBitMapForStringURL(imgSrcString,
                                ShowBigPic.this);
                    }

                    if (imgBm != null) {
                        handler.sendEmptyMessage(0);
                    } else {
                        handler.sendEmptyMessage(1);
                    }
                }
            }.start();
        } else {
            if (null != downloadimgSrcString
                    && !"".equals(downloadimgSrcString)
                    && PicUtil.isLocalPicExit(PicUtil.phototempDir,
                            downloadimgSrcString.substring(
                                    downloadimgSrcString.lastIndexOf("/") + 1,
                                    downloadimgSrcString.length()))) {
                hideLoadingLayout();

                WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(
                        PicUtil.readLocalJPEGFile(
                                PicUtil.phototempDir,
                                downloadimgSrcString.substring(
                                        downloadimgSrcString.lastIndexOf("/") + 1,
                                        downloadimgSrcString.length())));
                // 放大处理
                if (null != bitmapReference.get()) {
                    try {
                        Matrix matrix = new Matrix();
                        matrix.postScale(2.5f, 2.5f);
                        WeakReference<Bitmap> newbmp = new WeakReference<Bitmap>(
                                Bitmap.createBitmap(bitmapReference.get(), 0, 0,
                                        bitmapReference.get().getWidth(), bitmapReference.get()
                                                .getHeight(),
                                        matrix, true));
                        bigpicImg.setImageBitmap(newbmp.get());
                        bigpicImg.setWithHeigh(newbmp.get().getWidth(),
                                newbmp.get().getHeight());
                    } catch (Exception e) {
                        bigpicImg.setImageBitmap(null);
                    } catch (OutOfMemoryError error) {
                        bigpicImg.setImageBitmap(null);
                    }
                } else {
                    bigpicImg.setImageBitmap(null);
                }

                if (altString != null && !altString.equals("")) {

                    bigpicDesc.setVisibility(View.VISIBLE);
                    String t = altString;
                    if (1 == screentype)
                        t = t.length() > 22 ? t.substring(0, 20) + ".." : t;
                    bigpicDesc.setText(t);

                } else {
                    // bigpicDesc.setVisibility(View.GONE);
                }
                bigpicLinearLayout.setVisibility(View.VISIBLE);
            } else {
                handler.sendEmptyMessage(1);
            }
        }
    }

    private void findViewsById() {
        bigpicImg = (ShowBigView) findViewById(R.id.bigpic);

        bigpicImg.setScale(getWindow().getWindowManager().getDefaultDisplay()
                .getWidth(), getWindow().getWindowManager().getDefaultDisplay()
                .getHeight());

        bigpicImg.setCallBack(new onClickCallBack() {

            @Override
            public void onclick() {
                ShowBigPic.this.finish();

            }
        });

        // showpicButton=(ImageButton) findViewById(R.id.show_ori_image);
        slideTopIn = AnimationUtils.loadAnimation(this, R.anim.scale_in_out);
        slideTopOut = AnimationUtils.loadAnimation(this, R.anim.slide_top_out);

        bigpicDesc = (TextView) findViewById(R.id.bigpic_desc);
        downloadButton = (ImageButton) findViewById(R.id.download_button);
        loadingLayout = (LinearLayout) findViewById(R.id.loadingpic);
        bigpicLinearLayout = (FrameLayout) findViewById(R.id.bigpic_linearlayout);
    }

    private void setListeners() {
        bigpicImg.setOnClickListener(imgClickListener);
        downloadButton.setOnClickListener(downloadClickListener);
        // showpicButton.setOnClickListener(showPicClickListener);
    }

    private void hideLoadingLayout() {
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    private void showLoadingLayout() {
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    hideLoadingLayout();
                    synchronized (imgBm) {
                        bigpicImg.setImageBitmap(imgBm);
                        if (altString != null && !altString.equals("")) {
                            bigpicDesc.setVisibility(View.VISIBLE);
                            String t = altString;
                            if (1 == screentype)
                                t = t.length() > 22 ? t.substring(0, 20) + ".." : t;
                            bigpicDesc.setText(t);

                        } else {

                        }
                        bigpicLinearLayout.setVisibility(View.VISIBLE);
                        handler.post(new Runnable() {
                            public void run() {
                                PicUtil.saveMyBitmap(PicUtil.phototempDir,
                                        imgSrcString.substring(
                                                imgSrcString.lastIndexOf("/") + 1,
                                                imgSrcString.length()), imgBm);
                            };
                        });
                    }

                    break;
                case 1:
                    Toast.makeText(ShowBigPic.this, "打开图片失败！", Toast.LENGTH_SHORT)
                            .show();
                    bigpicImg.performClick();
                    ShowBigPic.this.finish();
                    break;
                case 2:
                    Toast.makeText(ShowBigPic.this, "成功下载到相册！", Toast.LENGTH_SHORT)
                            .show();
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                            Uri.parse("file://"
                                    + Environment.getExternalStorageDirectory())));
                    break;
                case 3:
                    Toast.makeText(ShowBigPic.this, "下载图片失败！", Toast.LENGTH_SHORT)
                            .show();
                case 4:
                    Toast.makeText(ShowBigPic.this, "没有SDCARD，不能查看原图！", Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
        }

    };

    private View.OnClickListener downloadClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            

        }
    };

    private View.OnClickListener showPicClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShowBigPic.this.finish();
        }
    };

    private View.OnClickListener imgClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShowBigPic.this.finish();
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (loadingLayout.getVisibility() == View.GONE)
                bigpicImg.performClick();
            else
                ShowBigPic.this.finish();
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getRepeatCount() > 1) {
            return super.onKeyDown(keyCode, event);
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            bigpicImg.performClick();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (imgBm != null) {
            imgBm.recycle();
            imgBm = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
    }

}
